<template>
  <div class="knowledge-base-container">
    <a-page-header
      title="知识库管理"
      sub-title="医学检测标准库"
      style="padding: 16px 0; background: #fff;"
    />
    
    <!-- 搜索与过滤区域 -->
    <a-card style="margin-bottom: 16px">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索检测项目、方法或标准..."
            style="width: 100%"
            @search="handleSearch"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="categoryFilter"
            placeholder="检测类别"
            style="width: 100%"
            @change="handleFilter"
            allow-clear
          >
            <a-select-option value="基因检测">基因检测</a-select-option>
            <a-select-option value="病理检测">病理检测</a-select-option>
            <a-select-option value="影像检测">影像检测</a-select-option>
            <a-select-option value="生化检测">生化检测</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="statusFilter"
            placeholder="状态筛选"
            style="width: 100%"
            @change="handleFilter"
            allow-clear
          >
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="deprecated">已弃用</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-range-picker 
            v-model:value="dateRange"
            style="width: 100%"
            @change="handleFilter"
          />
        </a-col>
        <a-col :span="4" style="text-align: right">
          <a-button type="primary" @click="showAddModal">
            <template #icon><plus-outlined /></template>
            添加检测标准
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <!-- 数据表格 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        :pagination="{ pageSize: 10, showSizeChanger: true, showTotal: (total: number) => `共 ${total} 条` }"
        row-key="id"
        :scroll="{ x: 1300 }"
      >
        <template #bodyCell="{ column, record }">
          <!-- 标准等级列 -->
          <template v-if="column.dataIndex === 'level'">
            <a-tag :color="getLevelColor(record.level)">{{ record.level }}</a-tag>
          </template>
          
          <!-- 状态列 -->
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="record.status === 'active' ? 'green' : 'red'">
              {{ record.status === 'active' ? '活跃' : '已弃用' }}
            </a-tag>
          </template>
          
          <!-- 参考来源列 -->
          <template v-if="column.dataIndex === 'source'">
            <a :href="record.sourceUrl" target="_blank">{{ record.source }}</a>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'operation'">
            <a-space>
              <a-button type="link" @click="showViewModal(record)">查看</a-button>
              <a-button type="link" @click="showEditModal(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除此检测标准吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 查看详情模态框 -->
    <a-modal
      v-model:visible="viewModalVisible"
      title="检测标准详情"
      :footer="null"
      width="800px"
    >
      <a-descriptions bordered :column="2">
        <a-descriptions-item label="检测项目">
          {{ currentRecord.name }}
        </a-descriptions-item>
        <a-descriptions-item label="检测类别">
          {{ currentRecord.category }}
        </a-descriptions-item>
        <a-descriptions-item label="检测方法">
          {{ currentRecord.method }}
        </a-descriptions-item>
        <a-descriptions-item label="标准等级">
          <a-tag :color="getLevelColor(currentRecord.level)">{{ currentRecord.level }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="参考来源">
          <a :href="currentRecord.sourceUrl" target="_blank">{{ currentRecord.source }}</a>
        </a-descriptions-item>
        <a-descriptions-item label="更新日期">
          {{ currentRecord.updateDate }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="currentRecord.status === 'active' ? 'green' : 'red'">
            {{ currentRecord.status === 'active' ? '活跃' : '已弃用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="标准版本">
          {{ currentRecord.version }}
        </a-descriptions-item>
        <a-descriptions-item label="检测标准描述" :span="2">
          {{ currentRecord.description }}
        </a-descriptions-item>
        <a-descriptions-item label="参考范围" :span="2">
          <div v-html="currentRecord.referenceRange"></div>
        </a-descriptions-item>
        <a-descriptions-item label="注意事项" :span="2">
          <div v-html="currentRecord.notes"></div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    
    <!-- 添加/编辑模态框 -->
    <a-modal
      v-model:visible="editModalVisible"
      :title="isEditing ? '编辑检测标准' : '添加检测标准'"
      @ok="handleEditSave"
      width="800px"
      :confirm-loading="submitLoading"
    >
      <a-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="检测项目" name="name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="检测类别" name="category">
          <a-select v-model:value="editForm.category">
            <a-select-option value="基因检测">基因检测</a-select-option>
            <a-select-option value="病理检测">病理检测</a-select-option>
            <a-select-option value="影像检测">影像检测</a-select-option>
            <a-select-option value="生化检测">生化检测</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="检测方法" name="method">
          <a-input v-model:value="editForm.method" />
        </a-form-item>
        <a-form-item label="标准等级" name="level">
          <a-select v-model:value="editForm.level">
            <a-select-option value="权威">权威</a-select-option>
            <a-select-option value="推荐">推荐</a-select-option>
            <a-select-option value="参考">参考</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="参考来源" name="source">
          <a-input v-model:value="editForm.source" />
        </a-form-item>
        <a-form-item label="来源链接" name="sourceUrl">
          <a-input v-model:value="editForm.sourceUrl" />
        </a-form-item>
        <a-form-item label="标准版本" name="version">
          <a-input v-model:value="editForm.version" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="editForm.status">
            <a-radio value="active">活跃</a-radio>
            <a-radio value="deprecated">已弃用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="检测标准描述" name="description">
          <a-textarea v-model:value="editForm.description" :rows="4" />
        </a-form-item>
        <a-form-item label="参考范围" name="referenceRange">
          <a-textarea v-model:value="editForm.referenceRange" :rows="4" />
        </a-form-item>
        <a-form-item label="注意事项" name="notes">
          <a-textarea v-model:value="editForm.notes" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { 
  PlusOutlined,
} from '@ant-design/icons-vue';

interface TestStandard {
  id: string;
  name: string;
  category: string;
  method: string;
  level: '权威' | '推荐' | '参考';
  source: string;
  sourceUrl: string;
  updateDate: string;
  status: 'active' | 'deprecated';
  version: string;
  description: string;
  referenceRange: string;
  notes: string;
}

// 表格列定义
const columns = [
  {
    title: '检测项目',
    dataIndex: 'name',
    key: 'name',
    width: 180,
    sorter: (a: TestStandard, b: TestStandard) => a.name.localeCompare(b.name)
  },
  {
    title: '检测类别',
    dataIndex: 'category',
    key: 'category',
    width: 120,
    filters: [
      { text: '基因检测', value: '基因检测' },
      { text: '病理检测', value: '病理检测' },
      { text: '影像检测', value: '影像检测' },
      { text: '生化检测', value: '生化检测' }
    ],
    onFilter: (value: string, record: TestStandard) => record.category === value,
  },
  {
    title: '检测方法',
    dataIndex: 'method',
    key: 'method',
    width: 150,
  },
  {
    title: '标准等级',
    dataIndex: 'level',
    key: 'level',
    width: 100,
    filters: [
      { text: '权威', value: '权威' },
      { text: '推荐', value: '推荐' },
      { text: '参考', value: '参考' }
    ],
    onFilter: (value: string, record: TestStandard) => record.level === value,
  },
  {
    title: '参考来源',
    dataIndex: 'source',
    key: 'source',
    width: 150,
  },
  {
    title: '更新日期',
    dataIndex: 'updateDate',
    key: 'updateDate',
    width: 120,
    sorter: (a: TestStandard, b: TestStandard) => new Date(a.updateDate).getTime() - new Date(b.updateDate).getTime(),
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '活跃', value: 'active' },
      { text: '已弃用', value: 'deprecated' }
    ],
    onFilter: (value: string, record: TestStandard) => record.status === value,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: 150,
  }
];

// 状态变量
const loading = ref(false);
const searchKeyword = ref('');
const categoryFilter = ref('');
const statusFilter = ref('');
const dateRange = ref<any[]>([]);
const viewModalVisible = ref(false);
const editModalVisible = ref(false);
const isEditing = ref(false);
const submitLoading = ref(false);
const currentRecord = ref<TestStandard>({} as TestStandard);
const testStandardList = ref<TestStandard[]>([]);
const editFormRef = ref();

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入检测项目名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择检测类别', trigger: 'change' }],
  method: [{ required: true, message: '请输入检测方法', trigger: 'blur' }],
  level: [{ required: true, message: '请选择标准等级', trigger: 'change' }],
  source: [{ required: true, message: '请输入参考来源', trigger: 'blur' }],
  version: [{ required: true, message: '请输入标准版本', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// 编辑表单
const editForm = reactive<TestStandard>({
  id: '',
  name: '',
  category: '',
  method: '',
  level: '参考',
  source: '',
  sourceUrl: '',
  updateDate: new Date().toISOString().split('T')[0],
  status: 'active',
  version: '',
  description: '',
  referenceRange: '',
  notes: ''
});

// 过滤后的数据
const filteredData = computed(() => {
  let result = [...testStandardList.value];
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.method.toLowerCase().includes(keyword) || 
      item.description.toLowerCase().includes(keyword)
    );
  }
  
  // 类别筛选
  if (categoryFilter.value) {
    result = result.filter(item => item.category === categoryFilter.value);
  }
  
  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value);
  }
  
  // 日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0]?.format?.('YYYY-MM-DD') || '';
    const endDate = dateRange.value[1]?.format?.('YYYY-MM-DD') || '';
    if (startDate && endDate) {
      result = result.filter(item => {
        const itemDate = item.updateDate;
        return itemDate >= startDate && itemDate <= endDate;
      });
    }
  }
  
  return result;
});

// 根据等级获取标签颜色
const getLevelColor = (level: string) => {
  switch (level) {
    case '权威': return 'red';
    case '推荐': return 'green';
    case '参考': return 'blue';
    default: return 'default';
  }
};

// 搜索处理
const handleSearch = () => {
  // 已通过计算属性实现
};

// 筛选处理
const handleFilter = () => {
  // 已通过计算属性实现
};

// 查看详情
const showViewModal = (record: TestStandard) => {
  currentRecord.value = { ...record };
  viewModalVisible.value = true;
};

// 显示添加模态框
const showAddModal = () => {
  isEditing.value = false;
  // 重置表单
  Object.keys(editForm).forEach(key => {
    // @ts-ignore
    editForm[key] = key === 'status' ? 'active' : key === 'level' ? '参考' : '';
  });
  editForm.id = `ts-${Date.now()}`;
  editForm.updateDate = new Date().toISOString().split('T')[0];
  
  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
  
  editModalVisible.value = true;
};

// 显示编辑模态框
const showEditModal = (record: TestStandard) => {
  isEditing.value = true;
  Object.assign(editForm, { ...record });
  
  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
  
  editModalVisible.value = true;
};

// 保存编辑/添加
const handleEditSave = () => {
  editFormRef.value.validate().then(() => {
    submitLoading.value = true;
    
    setTimeout(() => {
      if (isEditing.value) {
        // 更新现有记录
        const index = testStandardList.value.findIndex(item => item.id === editForm.id);
        if (index !== -1) {
          testStandardList.value[index] = { ...editForm };
        }
        message.success('检测标准更新成功');
      } else {
        // 添加新记录
        testStandardList.value.unshift({ ...editForm });
        message.success('检测标准添加成功');
      }
      
      editModalVisible.value = false;
      submitLoading.value = false;
    }, 500);
  }).catch(() => {
    message.error('请填写完整的表单信息');
  });
};

// 删除处理
const handleDelete = (record: TestStandard) => {
  const index = testStandardList.value.findIndex(item => item.id === record.id);
  if (index !== -1) {
    testStandardList.value.splice(index, 1);
    message.success('检测标准删除成功');
  }
};

// 模拟数据
const mockData = () => {
  testStandardList.value = [
    {
      id: 'ts-001',
      name: 'EGFR 基因突变检测',
      category: '基因检测',
      method: 'PCR 扩增测序法',
      level: '权威',
      source: '中国临床肿瘤学会 (CSCO)',
      sourceUrl: 'https://www.csco.org.cn',
      updateDate: '2023-12-15',
      status: 'active',
      version: 'v2023.2',
      description: 'EGFR 基因突变检测用于非小细胞肺癌患者靶向治疗的决策，主要检测外显子19缺失、外显子21 L858R点突变等常见突变。',
      referenceRange: '无突变：野生型<br>突变位点：外显子19缺失、外显子21 L858R、T790M耐药突变等',
      notes: '样本要求：新鲜组织、石蜡包埋组织、外周血等<br>检测限：突变丰度≥1%',
    },
    {
      id: 'ts-002',
      name: 'HER2 蛋白表达检测',
      category: '病理检测',
      method: '免疫组织化学法 (IHC)',
      level: '权威',
      source: '美国临床肿瘤学会 (ASCO)',
      sourceUrl: 'https://www.asco.org',
      updateDate: '2023-10-10',
      status: 'active',
      version: 'v2023.1',
      description: 'HER2 蛋白表达检测用于乳腺癌、胃癌等肿瘤靶向治疗的指导。',
      referenceRange: '0/1+：阴性<br>2+：可疑阳性<br>3+：阳性',
      notes: '2+结果需进一步FISH检测确认<br>需使用标准化的抗体和评分系统',
    },
    {
      id: 'ts-003',
      name: '肺部结节CT评估',
      category: '影像检测',
      method: '低剂量CT (LDCT)',
      level: '推荐',
      source: '美国放射学会 (ACR)',
      sourceUrl: 'https://www.acr.org',
      updateDate: '2023-09-05',
      status: 'active',
      version: 'v2023',
      description: '肺部结节CT评估用于肺部结节的发现、测量和随访，肺癌筛查的重要手段。',
      referenceRange: '结节大小分级：<br>微小结节：<5mm<br>小结节：5-10mm<br>中等大小结节：10-30mm<br>大结节：>30mm',
      notes: 'Lung-RADS评分系统用于结节分级和随访推荐<br>需结合临床和吸烟史综合评估',
    },
    {
      id: 'ts-004',
      name: '血糖测定',
      category: '生化检测',
      method: '己糖激酶法',
      level: '参考',
      source: '中华医学会检验医学分会',
      sourceUrl: 'https://www.chcams.ac.cn',
      updateDate: '2023-05-20',
      status: 'active',
      version: 'v2023',
      description: '血糖测定用于糖尿病的诊断和监测，是最基础的代谢检测项目之一。',
      referenceRange: '空腹血糖：3.9-6.1 mmol/L<br>餐后2小时血糖：<7.8 mmol/L',
      notes: '糖尿病诊断标准：<br>空腹血糖 ≥7.0 mmol/L<br>糖耐量试验2小时血糖 ≥11.1 mmol/L<br>随机血糖 ≥11.1 mmol/L + 典型症状',
    },
    {
      id: 'ts-005',
      name: 'ALK 融合基因检测',
      category: '基因检测',
      method: '荧光原位杂交法 (FISH)',
      level: '权威',
      source: '中国精准医学大肿瘤协作组',
      sourceUrl: 'https://www.ncctsscp.com',
      updateDate: '2023-08-12',
      status: 'active',
      version: 'v2023.1',
      description: 'ALK 融合基因检测用于非小细胞肺癌患者靶向治疗决策，主要检测 EML4-ALK 等融合基因。',
      referenceRange: '阴性：<15%的肿瘤细胞显示分离信号<br>阳性：≥15%的肿瘤细胞显示分离信号',
      notes: '样本要求：石蜡包埋组织切片<br>可通过IHC初筛，FISH确认',
    },
    {
      id: 'ts-006',
      name: '甲胎蛋白 (AFP) 测定',
      category: '生化检测',
      method: '化学发光免疫分析法',
      level: '推荐',
      source: '中华医学会肝病学分会',
      sourceUrl: 'https://www.cma.org.cn',
      updateDate: '2022-11-30',
      status: 'deprecated',
      version: 'v2022',
      description: '甲胎蛋白测定用于原发性肝细胞癌的筛查和监测，也用于评估胚胎发育。',
      referenceRange: '正常值：<20 ng/mL（成人）',
      notes: '需结合超声等影像学检查综合评估<br>已不推荐单独用于肝癌筛查，建议与超声联合应用',
    }
  ];
};

// 生命周期钩子
onMounted(() => {
  loading.value = true;
  // 模拟数据加载
  setTimeout(() => {
    mockData();
    loading.value = false;
  }, 800);
});
</script>

<style scoped>
.knowledge-base-container {
  padding: 0;
  width: 100%;
}
</style> 